<?php
class controller_index extends controller{
	public function _init() {
		L ( include APP_PATH . 'install/lang/common.php' );
		$install =  memory::has(IKPHP_DATA . 'install.lock');
		if($install){
			return $this->redirect('result/installed');
		}
	}
	public function index() { 
		if(IS_GET){
			$step = I('get.step'); session('step','rrrsss');
			if($step=='1'){ 
				//检测环境
				$this->assign('step', 1);
				$env_items = array
							(
								'os' => array('c' => 'PHP_OS', 'r' => 'notset', 'b' => 'unix'),
								'php' => array('c' => 'PHP_VERSION', 'r' => '5.1', 'b' => '5.3'),
								'attachmentupload' => array('r' => 'notset', 'b' => '2M'),
								'gdversion' => array('r' => '1.0', 'b' => '2.0'),
								'diskspace' => array('r' => '10M', 'b' => 'notset'),
							);
				env_check($env_items);
				    
				$env_str = $file_str = $dir_str = $func_str = '';
				$error_code = 0;
				foreach($env_items as $key => $item) {
					$status = 1;
					if($item['r'] != 'notset') {
						if(intval($item['current']) && intval($item['r'])) {
							if(intval($item['current']) < intval($item['r'])) {
								$status = 0;
								$error_code = 31;
							}
						} else {
							if(strcmp($item['current'], $item['r']) < 0) {
								$status = 0;
								$error_code = 31;
							}
						}
					}
					$env_str .= "<tr>\n";
					$env_str .= "<td>".L($key)."</td>\n";
					$env_str .= "<td class=\"padleft\">".L($item['r'])."</td>\n";
					$env_str .= "<td class=\"padleft\">".L($item['b'])."</td>\n";
					$env_str .= ($status ? "<td class=\"w pdleft1\">" : "<td class=\"nw pdleft1\">").$item['current']."</td>\n";
					$env_str .= "</tr>\n";
				}
				$this->assign('env_str',$env_str);
				
				$func_items = array(function_exists('mysql_connect') ? 'mysql_connect' : 'mysqli_connect', 'gethostbyname', 'file_get_contents', 'xml_parser_create');
				//函数检测
				foreach($func_items as $item) {
					$status = function_exists($item);
					$func_str .= "<tr>\n";
					$func_str .= "<td>$item()</td>\n";
					if($status) {
						$func_str .= "<td class=\"w pdleft1\">".L('supportted')."</td>\n";
						$func_str .= "<td class=\"padleft\">".L('none')."</td>\n";
					} else {
						$error_code = 31;
						$func_str .= "<td class=\"nw pdleft1\">".L('unsupportted')."</td>\n";
						$func_str .= "<td><font color=\"red\">".L('advice_'.$item)."</font></td>\n";
					}
				}
				$this->assign('func_str',$func_str);
				//检测扩展函数
				$filesock_items = array('fsockopen', 'pfsockopen', 'stream_socket_client', 'curl_init');
				$func_strextra = '';
				foreach($filesock_items as $item) {
					$status = function_exists($item);
					$func_strextra .= "<tr>\n";
					$func_strextra .= "<td>$item()</td>\n";
					if($status) {
						$func_strextra .= "<td class=\"w pdleft1\">".L('supportted')."</td>\n";
						$func_strextra .= "<td class=\"padleft\">".L('none')."</td>\n";
						break;
					} else {
						$func_strextra .= "<td class=\"nw pdleft1\">".L('unsupportted')."</td>\n";
						$func_strextra .= "<td><font color=\"red\">".L('advice_'.$item)."</font></td>\n";
					}
				}
				$this->assign('func_strextra',$func_strextra);	

				//目录检测
				$dirfile_items = array
				(
					'config_dir'   => array('type' => 'dir',  'path' => './config'),
					'config' 	   => array('type' => 'file', 'path' => './config/config.php'),
					'config_db'    => array('type' => 'file', 'path' => './config/db.php'),
					'config_tags'  => array('type' => 'file', 'path' => './config/tags.php'),
					'config_url'   => array('type' => 'file', 'path' => './config/url.php'),
					'config_user'  => array('type' => 'file', 'path' => APP_PATH.'user/config/config.php'),
					
					'data' 		 => array('type' => 'dir', 'path' => './data'),
					'upload'	 => array('type' => 'dir', 'path' => './data/upload'),
					'backdata' 	 => array('type' => 'dir', 'path' => './data/backdata'),
					'plugindata' => array('type' => 'dir', 'path' => './data/plugindata'),
					'plugindownload' => array('type' => 'dir', 'path' => './data/download'),
					
					'runtime' => array('type' => 'dir', 'path' => './runtime'),
					'cache' => array('type' => 'dir', 'path' => './runtime/cache'),
					'compiled_data' => array('type' => 'dir', 'path' => './runtime/data'),
					'logs' => array('type' => 'dir', 'path' => './runtime/logs'),
					'temp' => array('type' => 'dir', 'path' => './runtime/temp'),
				);
				dirfile_check($dirfile_items);
				foreach($dirfile_items as $key => $item) {
					$variable = $item['type'].'_str'; 
					$$variable .= "<tr>\n"; 
					$$variable .= "<td>$item[path]</td><td class=\"w pdleft1\">".L('writeable')."</td>\n";  
					if($item['status'] == 1) {
						$$variable .= "<td class=\"w pdleft1\">".L('writeable')."</td>\n";
					} elseif($item['status'] == -1) {
						$error_code = 31;
						$$variable .= "<td class=\"nw pdleft1\">".L('nodir')."</td>\n";
					} else {
						$error_code = 31;
						$$variable .= "<td class=\"nw pdleft1\">".L('unwriteable')."</td>\n";
					}
					$$variable .= "</tr>\n";					
				}
				$this->assign('dir_str',$dir_str);
				$this->assign('file_str',$file_str);
				$this->display();	
			}elseif ($step==2){
				return $this->redirect('index/next');
			}else{
				$this->assign('step', 0);
				$this->display();
			}
		}
	}
	//第二步
	public function next() {
		$this->assign ( 'step', '2' );
		if (IS_POST) {
			foreach ( $_POST as $key => $val ) {
				$this->assign ( $key, $val );
			}
			extract ( $_POST ); 
			
			$check = true;
			if (!$dbhost) {
				$this->assign ( 'dbhost_error_msg', L ( 'dbhost_error_msg' ) ); $check = false;
			}
			if (!$dbport) {
				$this->assign ( 'dbport_error_msg', L ( 'dbport_error_msg' ) ); $check = false;
			}			
			if(!$dbname){
				$this->assign ( 'dbname_error_msg', L ( 'dbname_error_msg' ) ); $check = false;
			}
			if(!$dbuser){
				$this->assign ( 'dbuser_error_msg', L ( 'dbuser_error_msg' ) ); $check = false;
			}
			if(!$dbprefix){
				$this->assign ( 'dbprefix_error_msg', L ( 'dbprefix_error_msg' ) ); $check = false;
			}

			if(!$sitename){
				$_POST['siteurl'] = '爱客网';
			}
			if(!$sitesubname){
				$_POST['sitesubname'] = '又一个爱客开源社区';
			}
									
			if(!$siteurl){
				$_POST['siteurl'] = $this->getHttpUrl();
			}
			
			if(!$username){
				$this->assign ( 'username_error_msg', L ( 'username_error_msg' ) ); $check = false;
			}elseif (strlen($username) > 15 || preg_match("/^$|^c:\\con\\con$|　|[,\"\s\t\<\>&]|^Guest/is", $username)) {
				$this->assign ( 'username_error_msg', L ( 'admin_username_invalid' ) ); $check = false;
			}		

			if(!$password){
				$this->assign ( 'password_error_msg', L ( 'password_error_msg' ) ); $check = false;
			}

			if($password != $password2){
				$this->assign ( 'password2_error_msg', L ( 'password2_error_msg' ) );	 $check = false;		
			}			
			if (! $this->_is_email ( $email )) {
				$this->assign ( 'email_error_msg', L ( 'admin_email_format_incorrect' ) ); $check = false;
			}
			if(!$check){ $this->display (); exit();}
			
			// 试着连接数据库
			$conn = @mysql_connect ( $dbhost . ':' . $dbport, $dbuser, $dbpwd );
			if (!$conn) {
				$this->assign ( 'error_msg', L ( 'connect_mysql_error' ) );
				$this->display ();
				exit ();
			}
			
			$selected_db = @mysql_select_db ( $dbname );
			
			if ($selected_db) {
				// 如果数据库存在 并且里面安装过 提示是否覆盖
				$query = @mysql_query ( "SHOW TABLES LIKE '{$dbprefix}%'" );
				$was_install = false;
				while ( $row = mysql_fetch_assoc ( $query ) ) {
					$was_install = true;
					break;
				}
				if ($was_install && ! isset ( $force_install )) {
					$this->assign ( 'force_install', true);
					$this->display ();
					exit ();
				} else {
					$this->_set_temp ( $_POST );
					$this->redirect('index/install?step=3');
				}
			} else {
				if (mysql_get_server_info ( $conn ) > '4.1') {
					$charset = C ( 'DEFAULT_CHARSET' );
					$sql = "CREATE DATABASE IF NOT EXISTS `{$dbname}` DEFAULT CHARACTER SET " . str_replace ( '-', '', $charset );
				} else {
					$sql = "CREATE DATABASE IF NOT EXISTS `{$dbname}`";
				}
				if (! mysql_query ( $sql, $conn )) {
					$this->assign ( 'error_msg', L ( 'create_db_error' ) );
					$this->display ();
					exit ();
				}
				$this->_set_temp ( $_POST ); 
				$this->redirect('index/install?step=3');
			}
		} else {

			$default_config = $_config = array();
			$default_configfile = APP_PATH .'install/config/config_db.php';
		
			if(!file_exists($default_configfile)) {
				exit('config_db.php was lost, please reupload this file.');
			} else {
				$default_config = include $default_configfile;
			}

			if(file_exists(CONF_PATH.'db.php')) {
				$_config = include CONF_PATH.'db.php';
			} else {
				$_config = $default_config;
			}

			$this->assign ( 'dbname', $_config['DB_NAME'] );
			$this->assign ( 'dbuser', $_config['DB_USER'] );
			$this->assign ( 'dbpwd',  '');
			$this->assign ( 'dbhost', $_config['DB_HOST'] );
			$this->assign ( 'dbport', $_config['DB_PORT'] );
			$this->assign ( 'dbprefix', $_config['DB_PREFIX'] );
			
			$this->assign ( 'sitename', '爱客网' );
			$this->assign ( 'sitesubname', '又一个爱客开源社区' );
			$this->assign ( 'siteurl', $this->getHttpUrl ());
			
			$this->assign ( 'email', 'admin@admin.com' );
			$this->assign ( 'password', '' );
			$this->assign ( 'password2', '' );
			$this->assign ( 'username', 'admin' );
			$this->display ();
		}
	}

	public function install() {
		$step = I('get.step');
		$temp_info = F ( 'temp_data' ); 
		if($step ==3&&!empty($temp_info)){
			$this->assign ( 'step', '3' ); 
			$this->display ();		
			$charset = C ( 'DEFAULT_CHARSET' );
			header ( 'Content-type:text/html;charset=' . $charset );
			$temp_info = F ( 'temp_data' );//缓存数据
			$conn = mysql_connect ( $temp_info ['dbhost'] . ':' . $temp_info ['dbport'], $temp_info ['dbuser'], $temp_info ['dbpwd'] );
			$version = mysql_get_server_info ();
		    $charset = str_replace('-', '', $charset);
	        if ($version > '4.1') {
	            if ($charset != 'latin1') {
	                mysql_query("SET character_set_connection={$charset}, character_set_results={$charset}, character_set_client=binary", $conn);
	            }if ($version > '5.0.1') {
	                mysql_query("SET sql_mode=''", $conn);
	            }
	        }
			$selected_db = mysql_select_db ( $temp_info ['dbname'], $conn );
			// 开始创建数据表
			$sqls = $this->_get_sql ( APP_PATH . 'install/data/install.sql' );

			foreach ( $sqls as $sql ) {
				// 替换前缀
				$sql = str_replace ( '`ik_', '`' . $temp_info ['dbprefix'], $sql );
				$run = mysql_query ( $sql, $conn );
				// 获得表名
				if (substr ( $sql, 0, 12 ) == 'CREATE TABLE') {
					$table_name = $temp_info ['dbprefix'] . preg_replace ( "/CREATE TABLE `" . $temp_info ['dbprefix'] . "([a-z0-9_]+)` .*/is", "\\1", $sql );
					showjsmsg(L('create_table').' '.$table_name.' ...... '.L('succeed'));
				}
			}
			
			//注册创始人帐号
			$auth_key  = build_auth_key();
			$admin_password = user_md5($temp_info['password'], $auth_key);
			$sql = "INSERT INTO `" . $temp_info['dbprefix'] . "admin` (`username`, `password`, `email`, `role_id`) VALUES " .
					"('" . $temp_info['username'] . "', '" . $admin_password . "', '" . $temp_info['email'] . "', 1);";		
			$userid = mysql_query( $sql, $conn );
			showjsmsg(L('create_admin').' '.$temp_info['dbprefix'].'admin ...... '.L('succeed'));
			
			
			//更改网站信息
			$run = mysql_query ( "UPDATE `" . $temp_info['dbprefix'] . "setting` set `data`='".$temp_info ['sitename']."' where `name`='site_title'", $conn );
			$run = mysql_query ( "UPDATE `" . $temp_info['dbprefix'] . "setting` set `data`='".$temp_info ['sitesubname']."' where `name`='site_subtitle'" , $conn );
			$run = mysql_query ( "UPDATE `" . $temp_info['dbprefix'] . "setting` set `data`='".$temp_info ['siteurl']."' where `name`='site_url'" , $conn );
	
			showjsmsg(L('create_setting').' '.$temp_info['dbprefix'].'admin ...... '.L('succeed'));
			
			//修改配置文件
			$DB = array();
			$DB['DB_TYPE'] = $temp_info['sql'];
			$DB['DB_HOST'] = $temp_info['dbhost'];
			$DB['DB_NAME'] = $temp_info['dbname'];
			$DB['DB_USER'] = $temp_info['dbuser'];
			$DB['DB_PWD'] = $temp_info['dbpwd'];
			$DB['DB_PORT'] = $temp_info['dbport'];
			$DB['DB_PREFIX'] = $temp_info['dbprefix'];
			//创建配置
			$conf = $this->write_config($DB, $auth_key);
			if($conf){
				showjsmsg(L('create_conf').' ...... '.L('succeed'));
				session('success',true);
				//安装完毕
				$this->redirect ('index/result');				
			}else{
				showjsmsg(L('create_conf').' ...... '.L('failed'));
			}				
		}else{
			$this->redirect('index/index');
		}
	}
	public function result() {
		if(session('success')){
        	@touch(IKPHP_DATA.'install.lock');
        	session('success',null);
	        $temp_info = F ( 'temp_data' );
	        $this->assign ( 'username', $temp_info['username'] );
	        $this->assign ( 'home_url', $temp_info['siteurl'] );
	        $this->assign ( 'admin_url',$temp_info['siteurl'].'index.php?app=admin' );
	        $this->assign ( 'password', $temp_info['password'] );
	        F ( 'temp_data', null );
	        $this->display();        	
		}else{
			$this->redirect('index/index');
		}
	}
	/**
	 * 写入配置文件
	 * @param  array $config 配置信息
	 */
	private function write_config($config, $auth){
		if(is_array($config)){
			//读取配置内容
			$conf   = file_get_contents(MODULE_PATH . 'data/conf.tpl');
			$user   = file_get_contents(MODULE_PATH . 'data/user.tpl');
			$dbconf = file_get_contents(MODULE_PATH . 'data/db.tpl');
			//替换配置项
			foreach ($config as $name => $value) {
				$conf = str_replace("[{$name}]", $value, $conf);
				$user = str_replace("[{$name}]", $value, $user);
				$dbconf = str_replace("[{$name}]", $value, $dbconf);
			}		
	
			$conf = str_replace('[AUTH_KEY]', $auth, $conf);
			$user = str_replace('[AUTH_KEY]', $auth, $user);
			$dbconf = str_replace('[AUTH_KEY]', $auth, $dbconf);
	
			//写入应用配置文件
			if(file_put_contents(ROOT_PATH . 'config/config.php', $conf) &&
			   file_put_contents(APP_PATH . 'user/config/config.php', $user) &&
			   file_put_contents(ROOT_PATH . 'config/db.php', $dbconf)
			   ){
				return true;
			} else {
				return false;
			}
	
		}
	}	
	private function _is_email($email) {
		$chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,5}\$/i";
		if (strpos ( $email, '@' ) !== false && strpos ( $email, '.' ) !== false) {
			if (preg_match ( $chars, $email )) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	private function _set_temp($temp_data) {
		F ( 'temp_data', $temp_data );
	}
	private function _get_sql($sql_file) {
		$contents = file_get_contents ( $sql_file );
		$contents = str_replace ( "\r\n", "\n", $contents );
		$contents = trim ( str_replace ( "\r", "\n", $contents ) );
		$return_items = $items = array ();
		$items = explode ( ";\n", $contents );
		
		foreach ( $items as $item ) {
			$return_item = '';
			$item = trim ( $item );
			$lines = explode ( "\n", $item );
			foreach ( $lines as $line ) {
				if (isset ( $line [1] ) && $line [0] . $line [1] == '--') {
					continue;
				}
				$return_item .= $line;
			}
			if ($return_item) {
				$return_items [] = $return_item; // .";";
			}
		}
		return $return_items;
	}
	//获取带http的网站域名 BY wanglijun
	private function getHttpUrl(){
		$arrUri = explode('install.php',$_SERVER['REQUEST_URI']);
		$site_url = 'http://'.$_SERVER['HTTP_HOST'].$arrUri[0];
		return $site_url;
	}	
}
